package com.tiantianyuegou.cash;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.tiantianyuegou.util.DateUtil;
import com.tiantianyuegou.util.LoadingDialog;
import com.tiantianyuegou.util.ToastUtilsCenter;
import com.trouble.framework.utils.MD5;
import com.tiantianyuegou.activity.BaseActivity;
import com.tiantianyuegou.R;
import com.tiantianyuegou.activity.AuthenticationActivity;
import com.tiantianyuegou.http.ApiDefine;
import com.tiantianyuegou.http.SPHelper;
import com.tiantianyuegou.view.pass.GridPasswordView;

import org.json.JSONException;
import org.json.JSONObject;

import cz.msebera.android.httpclient.Header;

/**
 * 提现密码输入框，及确认提现
 */
public class CashPasswordDialogFragment extends DialogFragment implements GridPasswordView.OnPasswordChangedListener, View.OnClickListener {

    public static final String EXTRA_CASHMONEY = "cashMoney";
    public static final String EXTRA_TBID = "tbId";
    public static final String EXTRA_DESP = "desp";
    private final AsyncHttpClient mHttpClient = new AsyncHttpClient();
    //密码输入框
    GridPasswordView mPasswordView;
    //键盘按钮
    private Button mBtn_1, mBtn_2, mBtn_3, mBtn_4, mBtn_5, mBtn_6, mBtn_7, mBtn_8, mBtn_9, mBtn_0;
    private ImageButton mBtn_delete, mBtn_dismiss;
    private TextView mTxt_forget;
    String tbId;
    String money;
    String time;
    int orderType;
    String orderId;
    String desp;
    private LoadingDialog loadingDialog;

    BaseActivity mBaseActivity;

    public interface iPayResultListener{
        void paySuccess();
    }

    private iPayResultListener listener;
    public void setPayResultListener(iPayResultListener listener){
        this.listener=listener;
    }


    void cancelPay() {
        dismiss();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_key_0:
                mPasswordView.appentPassWord("0");
                break;
            case R.id.btn_key_1:
                mPasswordView.appentPassWord("1");
                break;
            case R.id.btn_key_2:
                mPasswordView.appentPassWord("2");
                break;
            case R.id.btn_key_3:
                mPasswordView.appentPassWord("3");
                break;
            case R.id.btn_key_4:
                mPasswordView.appentPassWord("4");
                break;
            case R.id.btn_key_5:
                mPasswordView.appentPassWord("5");
                break;
            case R.id.btn_key_6:
                mPasswordView.appentPassWord("6");
                break;
            case R.id.btn_key_7:
                mPasswordView.appentPassWord("7");
                break;
            case R.id.btn_key_8:
                mPasswordView.appentPassWord("8");
                break;
            case R.id.btn_key_9:
                mPasswordView.appentPassWord("9");
                break;
            case R.id.btn_key_del:
                mPasswordView.deletePassWord();
                break;
            case R.id.img_dismiss:
                cancelPay();
                break;
            case R.id.paypwd_forget://忘记密码
                Intent intent = new Intent(getActivity(), AuthenticationActivity.class);
                startActivity(intent);
                //cancelPay();
                break;
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setStyle(STYLE_NO_TITLE, R.style.FilterDialogTheme);
        Bundle args = getArguments();
        if (args == null || !args.containsKey(EXTRA_CASHMONEY) || !args.containsKey(EXTRA_TBID)) {
            dismiss();
            return;
        }
        tbId = args.getString(EXTRA_TBID);
        money = args.getString(EXTRA_CASHMONEY);
        desp = args.getString(EXTRA_DESP);
        time = DateUtil.getDateTimenone();
    }

    @Override
    @Nullable
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_paypassword, container, false);
        initView(view);
        initListener();
        return view;
    }

    private void initListener() {
        mBtn_0.setOnClickListener(this);
        mBtn_1.setOnClickListener(this);
        mBtn_2.setOnClickListener(this);
        mBtn_3.setOnClickListener(this);
        mBtn_4.setOnClickListener(this);
        mBtn_5.setOnClickListener(this);
        mBtn_6.setOnClickListener(this);
        mBtn_7.setOnClickListener(this);
        mBtn_8.setOnClickListener(this);
        mBtn_9.setOnClickListener(this);
        mBtn_delete.setOnClickListener(this);
        mBtn_dismiss.setOnClickListener(this);
        mTxt_forget.setOnClickListener(this);
    }

    private void initView(View view) {
        mPasswordView = (GridPasswordView) view.findViewById(R.id.view_password);
        mBtn_0 = (Button) view.findViewById(R.id.btn_key_0);
        mBtn_1 = (Button) view.findViewById(R.id.btn_key_1);
        mBtn_2 = (Button) view.findViewById(R.id.btn_key_2);
        mBtn_3 = (Button) view.findViewById(R.id.btn_key_3);
        mBtn_4 = (Button) view.findViewById(R.id.btn_key_4);
        mBtn_5 = (Button) view.findViewById(R.id.btn_key_5);
        mBtn_6 = (Button) view.findViewById(R.id.btn_key_6);
        mBtn_7 = (Button) view.findViewById(R.id.btn_key_7);
        mBtn_8 = (Button) view.findViewById(R.id.btn_key_8);
        mBtn_9 = (Button) view.findViewById(R.id.btn_key_9);
        mBtn_delete = (ImageButton) view.findViewById(R.id.btn_key_del);
        mBtn_dismiss = (ImageButton) view.findViewById(R.id.img_dismiss);
        mTxt_forget = (TextView) view.findViewById(R.id.paypwd_forget);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mPasswordView.setOnPasswordChangedListener(this);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mBaseActivity = (BaseActivity) activity;
    }

    @Override
    @NonNull
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = super.onCreateDialog(savedInstanceState);
        dialog.getWindow().setGravity(Gravity.BOTTOM);
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(false);
        return dialog;
    }

    @Override
    public void onStart() {
        super.onStart();
        if (getDialog() != null) {
            getDialog().getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        }
    }

    @Override
    public void onChanged(String psw) {

    }

    //获取输入的密码
    @Override
    public void onMaxLength(String psw) {
        //cancelPay();
        loadPay(psw);
    }

    @Override
    public void onDestroyView() {
        mHttpClient.cancelRequests(getActivity(), true);
        super.onDestroyView();
    }

    //提现
    private void loadPay(String password) {

        loadingDialog = new LoadingDialog(getActivity());
        loadingDialog.setMsg("loading...");
        loadingDialog.show();
        RequestParams params = new RequestParams();
        params.put("tmId", SPHelper.getTmId());
        params.put("tbId", tbId);
        params.put("money", money);
        params.put("time", time);
        params.put("payPassword", password);
        String vcode = SPHelper.getTmId() + money + MD5.md5(SPHelper.getPassword()).toLowerCase() + tbId + time;
        params.put("vcode", vcode);
        params.put("desp", desp);
        params.put("key", "z1zkey");
        params.put("code", "MTJCNDgyOTIxOTk4QjUzQzM2QTlFN0ZFMzY0MDNEMjQ");
        mHttpClient.post(ApiDefine.TAKE_MONEY, params, new TextHttpResponseHandler() {

            @Override
            public void onStart() {
                super.onStart();
                loadingDialog.show();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                loadingDialog.dismiss();
            }

            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                Log.e("TAG", "failure response :" + s);
                Toast.makeText(mBaseActivity, "当前网络不可用，请检查您的网设置", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSuccess(int i, Header[] headers, String s) {
                Log.e("TAG", "cash money response:" + s);
                if (TextUtils.isEmpty(s)) {
                    Toast.makeText(getActivity(), "提现异常", Toast.LENGTH_SHORT).show();
                } else {
                    try {
                        JSONObject root = new JSONObject(s);
                        String code = root.getString("code");
                        if ("100".equals(code)) {
                            String msg = root.getString("message");
                          ToastUtilsCenter.makeText(mBaseActivity, msg, true).show();
                            cancelPay();
                            listener.paySuccess();
                        } else {
                            String msg = root.getString("message");
                            ToastUtilsCenter.makeText(mBaseActivity, msg, false).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

}
